package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.PublishVo;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * 圈子-服务接口实现类
 */
@Service
public class PublishApiImpl implements PublishApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    IdService idService;

    @Override
    public void save(PublishVo publishVo) {
        long commonTime = System.currentTimeMillis();
        //a.保存发布表
        Publish publish = new Publish();
        //将相同属性 copy 赋值
        BeanUtils.copyProperties(publishVo,publish);
        publish.setId(ObjectId.get());
        publish.setPid(idService.nextId("quanzi_publish"));//目前没有 可以省略
        publish.setLocationName(publishVo.getLocation());//地址位置
        publish.setSeeType(1); // 谁可以看，1-公开，2-私密，3-部分可见，4-不给谁看
        publish.setCreated(commonTime);
        mongoTemplate.save(publish);
        //b.保存相册表
        Album album = new Album();
        album.setId(ObjectId.get());
        album.setPublishId(publish.getId());//发布id
        album.setCreated(commonTime);
        mongoTemplate.save(album,"quanzi_album_"+publishVo.getUserId());

        //c.查询好友表 好友ids
        Query queryFriend = new Query();
        queryFriend.addCriteria(Criteria.where("userId").is(publishVo.getUserId()));//当前用户id作为条件
        List<Friend> friendList = mongoTemplate.find(queryFriend, Friend.class);

        //d.循环遍历往好友时间线表保存数据
        if(friendList != null && friendList.size()>0){
            for (Friend friend : friendList) {
                Long friendId = friend.getFriendId();//好友id  往好友时间线表写数据
                TimeLine timeLine = new TimeLine();
                timeLine.setUserId(publishVo.getUserId());//好友id 发布动态用户id
                timeLine.setPublishId(publish.getId());//发布id
                timeLine.setCreated(commonTime);//发布时间
                timeLine.setId(ObjectId.get());
                mongoTemplate.save(timeLine,"quanzi_time_line_"+friendId);
            }
        }

    }

    /**
     * 查询好友动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult<Publish> queryMovements(Long userId, int page, int pagesize) {
        //1.先查询时间线表
        //查询总记录数
        Query query = new Query().with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query,TimeLine.class,"quanzi_time_line_" + userId);
        //分页查询当前页面时间线表数据
        PageRequest pageable = PageRequest.of(page-1,pagesize, Sort.by(Sort.Order.desc("created")));
        query.with(pageable);
        List<TimeLine> timeLineList = mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        //2.再查询发布表
        if(timeLineList == null || timeLineList.size() == 0){
            return null;
        }
        //当前页面好友动态列表数据
        List<Publish> publishList = new ArrayList<>();
        for (TimeLine timeLine : timeLineList) {
            ObjectId publishId = timeLine.getPublishId();//发布表id
            if(publishId == null){
                continue;
            }
            Publish publish = mongoTemplate.findById(publishId, Publish.class);
            if(publish == null){
                continue;
            }
            publishList.add(publish);
        }
        //3.封装VO
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Publish>(counts,(long)pagesize,pages,(long)page,publishList);
    }

    /**
     * 查询推荐动态
     */
    @Override
    public PageResult<Publish> queryRecommend(Long userId, int page, int pagesize) {
        //1.先查询推荐动态表
        //查询总记录数 条件：查询推荐给当前登录用户
        Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize).skip((page - 1) * pagesize);
        long counts = mongoTemplate.count(query,RecommendQuanzi.class);
        List<RecommendQuanzi> recommendQuanziList = mongoTemplate.find(query, RecommendQuanzi.class);
        //2.再查询发布表
        if(recommendQuanziList == null || recommendQuanziList.size() == 0){
            return null;
        }
        //当前页面好友动态列表数据
        List<Publish> publishList = new ArrayList<>();
        for (RecommendQuanzi recommendQuanzi : recommendQuanziList) {
            ObjectId publishId = recommendQuanzi.getPublishId();//发布表id
            if(publishId == null){
                continue;
            }
            Publish publish = mongoTemplate.findById(publishId, Publish.class);
            if(publish == null){
                continue;
            }
            publishList.add(publish);
        }
        //3.封装VO
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Publish>(counts,(long)pagesize,pages,(long)page,publishList);
    }

    /**
     * 我的动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult<Publish> queryMyAlbum(Long userId, int page, int pagesize) {
        //1.先查询推荐动态表
        //查询总记录数 条件：查询推荐给当前登录用户
        //方式一：
        /*Query query = new Query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize).skip((page - 1) * pagesize);*/
        //方式二：
        PageRequest pageRequest = PageRequest.of(page-1,pagesize,Sort.by(Sort.Order.desc("created")));
        Query query = new Query();//不需要通过userId查询
        query.with(pageRequest);
        long counts = mongoTemplate.count(query,"quanzi_album_"+userId);
        List<Album> albumList = mongoTemplate.find(query,Album.class, "quanzi_album_"+userId);
        //2.再查询发布表
        if(albumList == null || albumList.size() == 0){
            return null;
        }
        //当前页面好友动态列表数据
        List<Publish> publishList = new ArrayList<>();
        for (Album album : albumList) {
            ObjectId publishId = album.getPublishId();//发布表id
            if(publishId == null){
                continue;
            }
            Publish publish = mongoTemplate.findById(publishId, Publish.class);
            if(publish == null){
                continue;
            }
            publishList.add(publish);
        }
        //3.封装VO
        long pages = counts/pagesize + counts%pagesize > 0 ? 1:0;
        return new PageResult<Publish>(counts,(long)pagesize,pages,(long)page,publishList);
    }

    /**
     * 查询单条动态
     */
    @Override
    public Publish queryById(String publishId) {
        return mongoTemplate.findById(publishId, Publish.class);
    }
}
